package com.leetcode.dataStruct.tree;

import com.leetcode.dataStruct.Node;

import java.util.LinkedList;

public class ConnectNext {
    public Node connect(Node root) {
        if (root == null) {
            return null;
        }
        LinkedList<Node> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            int levelSize = queue.size();
            Node preNode = null;
            for (int i = 0; i < levelSize; i++) {
                Node curNode = queue.poll();
                if (preNode != null) {
                    preNode.next = curNode;
                }
                if (curNode.left != null) {
                    queue.offer(curNode.left);
                }
                if (curNode.right != null) {
                    queue.offer(curNode.right);
                }
                preNode = curNode;
            }
        }
        return root;
    }
}
